package org.eclipse.wtp.sample.flashcards;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EditDictionaryServlet extends HttpServlet implements Servlet {
	
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// make sure we can get special characters
		if (request.getCharacterEncoding() == null)
			request.setCharacterEncoding("UTF-8");
		
		// read data from form
		String newKey1 = request.getParameter("key1");
		String newKey2 = request.getParameter("key2");
		String mode = request.getParameter("mode");

		// reset message
		request.getSession().setAttribute("message", "");

		// get reference to active dictionary
		FlashCardSet localset = (FlashCardSet)request.getSession().getAttribute("flashcardset");
		
		// test for empty set
		if (localset == null) {
			request.getSession().setAttribute("message", "invalid dictionary loaded");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/edit.jsp");
			dispatcher.forward(request,response);
			return;
		}
		
		if (mode.equals("Add Word")) {
			// add word to dictionary
			System.out.println("Adding word: " + newKey1 + "::" + newKey2);

			localset.addCard(newKey1, newKey2,"");
			request.getSession().setAttribute("message", newKey1 + "::" + newKey2 + " successfully added");
			
			// update dictionary file
			response.setContentType("text/html");
			String filename = localset.getFilename();
			ServletContext context = getServletContext();
			String path = context.getRealPath("/data/");
			System.out.println("new path:" + path);
			System.out.println("making file:" + path + "/" + filename);
			FileWriter fstream = new FileWriter(path + "/" + filename);
			BufferedWriter out = new BufferedWriter(fstream);
			localset.save(out);
			out.close();
		}
		else if (mode.equals("Delete Entry")) {
			String input = request.getParameter("Dictionary Contents");
			int divider = input.indexOf("::");
			int length = input.length();
			
			String word1 = input.substring(0, divider);
			String word2 = input.substring(divider + 2, length);
			
			System.out.println("Input: " + input);
			System.out.println("Divider at index: " + divider);
			System.out.println("Removing pair: " + word1 + "  " + word2);
			
			localset.remove(word1, word2);
			
			// update dictionary file
			response.setContentType("text/html");
			String filename = localset.getFilename();
			ServletContext context = getServletContext();
			String path = context.getRealPath("/data/");
			System.out.println("new path:" + path);
			System.out.println("making file:" + path + "/" + filename);
			FileWriter fstream = new FileWriter(path + "/" + filename);
			BufferedWriter out = new BufferedWriter(fstream);
			localset.save(out);
			out.close();

		}
		else if (mode.equals("Order by Key 1")) {
			localset.sort(1);
		}
		else if (mode.equals("Order by Key 2")) {
			localset.sort(2);
		}
		else if (mode.equals("Delete Dictionary")) {
			// collect other dictionary names from file
			String currentName = localset.getTitle();//(String)request.getSession().getAttribute("loadedsetname");
			ArrayList<String> dictionaries = new ArrayList<String>();
			
			response.setContentType("text/html");
			String filename = "/data/dictionaries.txt";
			ServletContext context = getServletContext();
			InputStream inp = context.getResourceAsStream(filename);
			if (inp != null) {
				InputStreamReader isr = new InputStreamReader(inp);
				BufferedReader reader = new BufferedReader(isr);
				String title = "";
				// read each entry
				while ((title = reader.readLine()) != null) {
					if (!title.equals(currentName)) {
						// add name to list of valid dictionaries
						dictionaries.add(title);
					}
				}
				reader.close();
			}	
			// write list of still valid dictionaries (all but current dictionary)
			response.setContentType("text/html");
			filename = "/data/dictionaries.txt";
			context = getServletContext();
			String path = context.getRealPath(filename);
			FileWriter fstream = new FileWriter(path);
			BufferedWriter out = new BufferedWriter(fstream);
			//out.write("Spanish-English" + "\n");
			//out.write("French-English" + "\n");
			Iterator<String> itr = dictionaries.iterator();
			while (itr.hasNext()){
				out.write(itr.next() + "\n");
			}
			out.close();
			
			// remove dictionary from dictionary list registered with Session
			ArrayList<String> dictionarylist = (ArrayList<String>)request.getSession().getAttribute("dictionarylist");
			
			itr = dictionarylist.iterator();
			while (itr.hasNext()) {
				String testtitle = (String)itr.next();
				if (testtitle.equals(currentName)) {
					itr.remove();
				}
			}

			
			// update Session attributes
			request.getSession().removeAttribute("DD" + currentName);
			request.getSession().removeAttribute("flashcardset");
			
			// redirect to main page
			getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
			return;

		}
		else {
			// default behavior
		}
		
		// redirect to edit page
		getServletContext().getRequestDispatcher("/edit.jsp").forward(request, response);


	}


}
